<template>
  <view class="content">
    <!-- 轮播图 -->
    <banner></banner>
    <!-- 功能选择框 -->
    <layout :is_login="is_login"></layout>
    <introduction :productPic="productPic"></introduction>
    <achievement :productPic="productPic"></achievement>
  </view>
</template>

<script>
// 轮播图
import banner from "@/components/banner/banner.vue";
// 功能选择区域
import layout from "@/components/index/Layout.vue";
// 产品介绍
import introduction from "@/components/index/introduction.vue";
import achievement from "@/components/index/Achievement.vue";
// 引入请求模块
import { getRequest, getAlarmInfo, postRequest } from "@/api/api.js";
// 引入url
import {
  proPicUrl,
  alertingRecode,
  alarmMonitor,
  alarmRecode,
} from "@/api/request.js";

export default {
  components: {
    // 轮播图
    banner,
    // 功能栏
    layout,
    // 产品介绍
    introduction,
    achievement,
  },
  data() {
    return {
      productPic: [],
      is_login: false,
      timerNum: 0,
      datastreams: [],
      alermInfo: {},
      isAlerming: false,
    };
  },
  onShow() {
    this.changeAlertState(false);
  },
  onLoad() {
    console.log("index ------- onLoad");
    // 获取产品图片
    this.getProPic();
    // 判断用户是否登录
    this.getUserInfo();
  },
  methods: {
    async getProPic() {
      // 发送get请求获取产品介绍图片
      console.log("--------getProPic1--------");
      await getRequest(proPicUrl)
        .then((result) => {
          this.productPic = result[1].data.data;
          console.log("--------getProPic2--------");
        })
        .catch((err) => {
          console.log(err);
          console.log("--------getProPic3--------");
        });
    },
    getUserInfo() {
      uni.getStorage({
        key: "userInfo",
        success: (res) => {
          // 检测登录是否过期
          this.checksession();
        },
        fail: (err) => {
          console.log("用户未登录" + err);
        },
      });
    },
    // 获取对应的报警信息
    getAlarm(datastreams) {
      const that = this;
      const alarmInfo = {};
      datastreams.forEach((item) => {
        if (item.id == "latitude") {
          alarmInfo.latitude = item.datapoints[0].value;
        } else if (item.id == "longitude") {
          alarmInfo.longitude = item.datapoints[0].value;
        } else if (item.id == "level") {
          alarmInfo.level = item.datapoints[0].value;
        } else if (item.id == "cause") {
          alarmInfo.cause = item.datapoints[0].value;
        } else if (item.id == "status") {
          alarmInfo.status = item.datapoints[0].value;
        } else if (item.id == "time") {
          alarmInfo.time = item.datapoints[0].value;
        } else if (item.id == "on_buzzer") {
          alarmInfo.on_buzzer = item.datapoints[0].value;
        }
      });
      console.log(alarmInfo);
      return alarmInfo;
    },
    // 监听是否有报警信息
    async watchAlerm() {
      if (this.is_login) {
        const that = this;
        // 设置定时器 10秒监测一次报警信息
        that.timerNum = setInterval(async function () {
          if (!that.isAlerming) {
            const result = await getAlarmInfo(alarmMonitor);
            console.log(result);
            if (result[1].data.errno == 0) {
              that.alermInfo = that.getAlarm(result[1].data.data.datastreams);
              console.log(that.alermInfo);
              that.alermInfo.time = that.$options.filters["dateFormat"](
                new Date()
              );
              if (that.alermInfo.status == 0) {
                that.isAlerming = true;
                uni.vibrateLong({
                  success: function () {
                    console.log("success");
                  },
                  fail: (err) => {
                    console.log(err);
                  },
                });

                if (that.alermInfo.level == 3) {
                  uni.showToast({
                    icon: "none",
                    title: "发现高级警报，正在跳转详情页面！",
                    duration: 1000,
                  });
                  uni.redirectTo({
                    url: `/pages/index/alerm?alermInfo=${JSON.stringify(
                      that.alermInfo
                    )}`,
                    success() {
                      clearInterval(that.timerNum);
                    },
                    fail: (err) => {
                      console.log(err);
                    },
                  });
                } else {
                  let level = that.alermInfo.level == 2 ? "中级" : "低级";
                  console.log(level);
                  uni.showModal({
                    title: "警报",
                    content: `发现${level}警报，是否跳转详情页面？`,
                    success(res) {
                      if (res.confirm) {
                        uni.redirectTo({
                          url: `/pages/index/alerm?alermInfo=${JSON.stringify(
                            that.alermInfo
                          )}`,
                          success() {
                            clearInterval(that.timerNum);
                          },
                          fail: (err) => {
                            console.log(err);
                          },
                        });
                      } else if (res.cancel) {
                        that.isAlerming = false;
                        console.log("用户点击取消");
                      }
                    },
                  });
                }
                // const result = await postRequest(alarmRecode, that.alermInfo);
                // console.log(result);
              }
            }
          }
        }, 1000 * 10);
        /* 
        that.timerNum = setInterval(async function () {
          const result = await getAlarmInfo(alarmMonitor);
          console.log(result);
          if (result[1].data.data.error == 0) {
            that.datastreams = result[1].data.data.datastreams;
            that.datastreams.forEach((item) => {
              console.log(item)
              if(item.id == "level") {

              }
            })
            uni.vibrateLong({
              success: function () {
                console.log("success");
              },
              fail: (err) => {
                console.log(err);
              },
            });
            if (result[1].data.data[0].level == "height") {
              uni.showToast({
                // icon: "none",
                title: "发现高级警报，正在跳转详情页面！",
                duration: 1000,
              });
              uni.redirectTo({
                url: "/pages/index/alerm",
                success() {
                  clearInterval(that.timerNum);
                },
                fail: (err) => {
                  console.log(err);
                },
              });
            } else {
              let level =
                result[1].data.data[0].level == "medium" ? "中级" : "低级";
              console.log(level);
              uni.showModal({
                title: "警报",
                content: `发现${level}警报，是否跳转详情页面？`,
                success(res) {
                  if (res.confirm) {
                    uni.redirectTo({
                      url: `/pages/index/alerm?alermInfo=${JSON.stringify(
                        that.alermInfo
                      )}`,
                      success() {
                        clearInterval(that.timerNum);
                      },
                      fail: (err) => {
                        console.log(err);
                      },
                    });
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                },
              });
            }
          }
        }, 1000 * 10);
        */
      }
    },

    // 检测登录是否过期
    checksession() {
      uni.checkSession({
        success: () => {
          this.is_login = true;
          // 监听报警信息
          this.watchAlerm();
        },
        fail: () => {
          uni.removeStorage({
            key: "token",
            success: () => {
              uni.removeStorage({
                key: "userInfo",
                success: () => {
                  console.log("已移除过期登录信息!");
                },
                fail: (err) => {
                  console.log(err);
                },
              });
            },
            fail: (err) => {
              console.log(err);
            },
          });
          uni.showToast({
            icon: "none",
            title: "登录已过期，请重新登录！",
            duration: 2000,
          });
        },
      });
    },
    changeAlertState(value) {
      this.isAlerming = value;
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  background-color: aliceblue;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
/* .content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    .logo {
        height: 200rpx;
        width: 200rpx;
        margin: 200rpx auto 50rpx auto;
    }
    
    .text-area {
        display: flex;
        justify-content: center;
    }
    
    .title {
        font-size: 36rpx;
        color: #8f8f94;
    } */
</style>